package DataStructure.queue;


//链队列
public class LinkQueue<E> implements MyQueue<E>{
    private Node head;//头节点
    private Node tail;//尾节点
    private int size;

    private class Node{
        private E e;
        private Node next;

        public Node(Node next) {
            this.next=next;
        }

        public Node(E e, Node next){
            this.e=e;
            this.next=next;
        }
    }

    public LinkQueue() {
        head=new Node(null);
        tail=head;
        size=0;
    }
    @Override
    public E first() {
        if(isEmpty())
            return null;
        return head.next.e;
    }

    @Override
    public E last() {
        if(isEmpty())
            return null;
        return tail.e;
    }

    @Override
    public void push(E e) {
        tail.next=new Node(e,null);
        tail=tail.next;
        size++;
    }

    @Override
    public E poll() {
        if(isEmpty())
            return null;
        Node tmp=head.next;
        head.next=tmp.next;
        size--;
        if(isEmpty())
            tail=head;
        return tmp.e;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }

    @Override
    public void clear() {
        head=new Node(null);
        tail=head;
        size=0;
    }

    @Override
    public String toString() {
        StringBuilder sb=new StringBuilder("[");
        if(!isEmpty()){
            Node cur=head.next;
            while(cur!=null){
                sb.append(cur.e).append(",");
                cur=cur.next;
            }
            sb.deleteCharAt(sb.length()-1);
        }
        sb.append("]");

        return "LinkQueue{" +
                "head=" + sb +
                ", size=" + size +
                '}';
    }
}
